<?php
namespace ac\modules\developer\controllers;

use Yii;
use ac\controllers\AuthController;
use app\modules\developer\models\Menu;
use app\modules\developer\models\MenuSearch;
use app\modules\developer\models\VueRouter;
use ac\component\exception\ErrMap;
use ac\component\tool\Tool;
use app\models\OperationLog;
use ac\behaviors\Sort;


class MenuController extends AuthController
{

    public function behaviors()
    {
        return [
             // 注册匿名行为，只有行为类名
            Sort::className(),

        ];
    }

	/*菜单列表*/
    public function actionMenuList()
    {
        // P($this->permissions);
        // P($this->userInfo);
        if($this->userInfo['issuper'] == 2){//普通身份 普通身份是以划分的权限取出的菜单
            $perIds = [];
            if(count($this->permissions) > 0){
                foreach($this->permissions as $k => $v){
                    array_push($perIds, $v['mid']);
                }
            }
            // P($perIds);
            $this->get['id'] = $perIds;
            // P($this->get);
        }
        $search = (new MenuSearch())->search($this->get);
        if($search === false){//验证搜索参数不通过
            $count = 0;
            $menuList = array();
        }else{
            if(isset($this->get['type']) and $this->get['type'] == 'ele'){
                $flag = 'ele';
            }else{
                $flag = '';
            }
            if(isset( $this->get['parentid'] )){
                $parentid = $this->get['parentid'];
            }else{
                $parentid = 0;
            }
            $menuList = Menu::getTreeList($search, $flag, $parentid, $this->userInfo['admin_id'], $this->userInfo['issuper'], $this->permissions);
        }
        // P($menuList);
        return Tool::showRes([0, '获取成功'], $menuList);
    }

    /*添加菜单*/
    public function actionAddMenu()
    {
        if(Yii::$app->request->isPost){
            /*判断parentid是否存在, ?这里暂不做判断，因为模型里做了判断*/
            // if(isset($this->post['Menu']['parentid']) and !$this->checkHasParId($this->post['Menu']['parentid'])){
            //     $this->post['Menu']['parentid'] = 0;
            // }
            // P($this->post['VueRouter']);
            $menu = new Menu;
            $transaction = Yii::$app->db->beginTransaction();//事物处理
            $pass = true;
            try{
                if($id = $menu->addMenu($this->post)){
                    if(!empty($this->post['VueRouter']['path'])
                     and !empty($this->post['VueRouter']['name']) 
                     and !empty($this->post['VueRouter']['component'])){
                        /*添加VUE 路由*/
                        $vueRouter = new VueRouter;
                        if(!$vueRouter->addRouter($this->post, $id)){
                            $pass = false;
                            if($vueRouter->hasErrors()){
                                $backInfo = ErrMap::getError(10005);//返回信息
                                $exception = $vueRouter->getErrors();//异常信息
                            }
                        }
                    }
                }else{
                    if($menu->hasErrors()){
                        $pass = false;
                        $backInfo = ErrMap::getError(10005);//返回信息
                        $exception = $menu->getErrors();//异常信息
                        // if(array_key_exists("apikeyname", $exception)){
                        //     $backInfo = ErrMap::getError(10017);//返回信息
                        // };
                    }
                }
                if($pass){
                    $backInfo = [0, '添加菜单成功'];//返回信息
                    $transaction->commit();
                }
            }catch(\Exception $exception){
                $transaction->rollback();       
            };
        };

        if(!isset($backInfo)){
            $backInfo = ErrMap::getError(10005);//返回信息
        }
        if(!isset($exception)){
            $exception = '';//异常信息
        }
        //操作日志
        if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
            return $res;
        };
    }

    /*
    修改菜单
    $flag               值为setState时 作用是更改状态，为空是修改菜单信息（更改菜单状态的方法调用传参）
    $successBackInfo    成功的返回信息（更改菜单状态的方法调用传参）
    */
    public function actionModifyMenu($flag = '', $successBackInfo = '')
    {
        /*取出单个数据*/
        if(Yii::$app->request->isGet){
            $id = isset($this->get['id'])?$this->get['id']:'';
            if($id){
                $menu = Menu::find()->joinWith('vueRouter')
                        ->where('id = :id', [':id' => $id])->asArray()->one();
                if(!is_null($menu)){
                    return Tool::showRes([0, '获取成功'], $menu);
                }else{
                    return Tool::showRes(ErrMap::getError(10010));
                };
            }
        }

        /*如果有数据，进行修改*/
        if(Yii::$app->request->isPost){
            $id = isset($this->post['Menu']['id'])?intval($this->post['Menu']['id']):'';
            if(!$id){
                $backInfo = ErrMap::getError(10005);//返回信息
            }else{
                /*判断parentid是否存在? ?这里暂不做判断，因为模型里做了判断*/
                // if(isset($this->post['Menu']['parentid']) and !$this->checkHasParId($this->post['Menu']['parentid'])){
                //     unset($this->post['Menu']['parentid']);
                // }
                // P($this->post['Menu']);

                $menu = new Menu;
                if(empty($flag)){
                    $successBackInfo = '修改菜单成功';//修改企业信息
                }
                $transaction = Yii::$app->db->beginTransaction();//事物处理
                $pass = true;
                try{
                    if(!$menu->modifyMenu($this->post, $id, $flag)){
                        $pass = false;
                        if($menu->hasErrors()){
                            $backInfo = ErrMap::getError(10005);//返回信息
                            $exception = $menu->getErrors();//异常信息
                        }
                    }

                    if($pass){
                        if(empty($flag)){
                            if(!empty($this->post['VueRouter']['path'])
                             and !empty($this->post['VueRouter']['name']) 
                             and !empty($this->post['VueRouter']['component'])){
                                /*添加、修改VUE 路由*/
                                $vueRouter = new VueRouter;
                                if($pass and !$vueRouter->addRouter($this->post, $id)){
                                    $pass = false;
                                    if($vueRouter->hasErrors()){
                                        $backInfo = ErrMap::getError(10005);//返回信息
                                        $exception = $vueRouter->getErrors();//异常信息
                                    }
                                }
                            }else{
                                $vueRouter = new VueRouter;
                                $vueRouter->deleteAll('menuid = :id', [':id' => $id]);
                            }
                        }
                    }
                    
                    if($pass){
                        $backInfo = [0, $successBackInfo];//返回信息
                        $transaction->commit();
                    }
                }catch(\Exception $exception){
                    $transaction->rollback();       
                };

            }

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };

        }

        return Tool::showRes(ErrMap::getError(10005));
    }

    /*1-全部显示2-导航显示-3头部菜案4-内页显示（显示标识操作）*/
    public function actionSetShowflag()
    {
        return $this->actionModifyMenu('setShowflag', '设置菜单状态成功');
    }

    /*是否显示1-不显示-2显示（是否显示操作）*/
    public function actionSetDisplay()
    {
        return $this->actionModifyMenu('setDisplay', '设置菜单状态成功');
    }

    /*
    排序
    tree型数据，是按照sort正序排列
    */
    public function actionSetSort()
    {
       if(Yii::$app->request->isPost){
            // P($this->post);
            //取出被排序的数据
            $sortId = isset($this->post['sort'])?$this->post['sort']:'';
            //目标对象  ‘before’在之上面，否则在下面
            $targetId = isset($this->post['target'])?$this->post['target']:'';
            if($sortId and $targetId){
                if($this->setSortTreeList(new Menu, $sortId, $targetId, $this->post['location'])){
                    $backInfo = [0, '设置菜单排序成功'];//返回信息
                }
            }
            // P($backInfo);

            if(!isset($backInfo)){
                $backInfo = ErrMap::getError(10005);//返回信息
            }
            if(!isset($exception)){
                $exception = '';//异常信息
            }
            //操作日志
            if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), $exception) ) != 'boolean'){
                return $res;
            };


       }
       return Tool::showRes(ErrMap::getError(10005));
    }


    /*删除菜单,包括子栏目（真删除）*/
    public function actionDeleteMenu()
    {
        $id = isset($this->get['id'])?$this->get['id']:'';
        if($id){
            $menu = new Menu;
            if(($res = $menu->deleteMenu($id)) === true){
                $backInfo = [0, '删除菜单成功'];//返回信息
                //操作日志
                if(gettype( $res = OperationLog::addLog($this->operationLogArgs($backInfo), '') ) != 'boolean'){
                    return $res;
                };
            }else{
                return Tool::showRes(ErrMap::getError($res));
            }
        }
        return Tool::showRes(ErrMap::getError($res));
    }

    /*检查父ID是否存在*/
    private function checkHasParId($id)
    {
        if($id == 0){
            return true;
        }
        $menu = Menu::find()->where('id = :id', [':id' => $id])->one();
        // P($menu);
        if(is_null($menu)){
            return false;
        }else{
            return true;
        };
    }



}